package exam.wzb.jsp.utils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.logging.Filter;
import java.util.logging.LogRecord;

public class LoginFilter implements Filter {


    public void init(FilterConfig filterConfig) throws ServletException {
        // 过滤器初始化，可以在这里执行一些配置操作，但在这个例子中我们不需要做什么
    }


    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;
        HttpSession session = req.getSession();

        // 检查是否需要登录
        String path = req.getRequestURI();
        if (!path.equals("/views/login.jsp") && !path.equals("/login") && session.getAttribute("user") == null) {
            // 如果用户未登录并且尝试访问非登录页面，则重定向到登录页面
            res.sendRedirect("/src/main/webapp/WEB-INF/login.jsp?error=true");
        } else {
            // 如果用户已登录或尝试访问登录页面，则继续执行后续过滤器或请求
            chain.doFilter(request, response);
        }

    }

    @Override
    public boolean isLoggable(LogRecord record) {
        return false;
    }
}
